package com.sky.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.Dao.EmployeeDao;
import com.sky.Service.EmployeeService;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordEditFailedException;
import com.sky.exception.PasswordErrorException;
import com.sky.result.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl
        extends ServiceImpl<EmployeeDao, Employee>
        implements EmployeeService {

    @Autowired
    private EmployeeDao employeeDao;

    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //1、根据用户名查询数据库中的数据
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<> ();
        queryWrapper.eq(Employee::getUsername,username);
        Employee employee = employeeDao.selectOne(queryWrapper);
        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码比对
        //  后期需要进行md5加密，然后再进行比对
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //3、返回实体对象
        return employee;
    }

    @Override
    public void addEmployee(EmployeeDTO employeeDTO) {
        //新建一个Employee对象
        Employee employee=new Employee();
        //属性拷贝
        BeanUtils.copyProperties(employeeDTO,employee);
        //处理status和password
        employee.setStatus(StatusConstant.ENABLE);
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //保存员工信息到数据库
        employeeDao.insert(employee);
    }

    //TODO 分页逻辑还需要修改
    @Override
    public PageResult getByPage(EmployeePageQueryDTO employeePageQueryDTO) {

        IPage<Employee> page=new Page<>(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        //创建条件构造器
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<> ();
        //添加查询条件
        queryWrapper.like(employeePageQueryDTO.getName()!=null,Employee::getName,employeePageQueryDTO.getName());
        //按照字母顺序排序，如果一样的话，按照创建时间倒序
        queryWrapper.orderByAsc(Employee::getName).orderByDesc(Employee::getCreateTime);
        //分页查询
        employeeDao.selectPage(page, queryWrapper);

        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getRecords());

        return pageResult;
    }

    @Override
    public void updateEmployeeStatus(Integer status,Long id) {
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<> ();
        queryWrapper.eq(Employee::getId,id);
        Employee employee = employeeDao.selectOne(queryWrapper);
        employee.setStatus(status);
        employeeDao.updateById(employee);
    }

    @Override
    public Employee getEmployeeById(Long id) {
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<> ();
        queryWrapper.eq(Employee::getId,id);
        Employee employee = employeeDao.selectOne(queryWrapper);
        return employee;

    }

    @Override
    public void updateEmployeeInfo(EmployeeDTO employeeDTO) {
        Employee employee = employeeDao.selectById(employeeDTO.getId());
        System.out.println("更新前employee1:"+employee);

        BeanUtils.copyProperties(employeeDTO,employee);
        //更新修改时间
        employee.setUpdateTime(LocalDateTime.now());
        //更新修改人
        employee.setUpdateUser(BaseContext.getCurrentEmpId());

        System.out.println("更新后employee1:"+employee);
        employeeDao.updateById(employee);

    }

    @Override
    public void modifyEmployeePassword(PasswordEditDTO passwordEditDTO) {
        //查询员工信息
        Employee employee = employeeDao.selectById(passwordEditDTO.getEmpId());
        //判断输入的旧密码是否正确
        String s = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        if(!s.equals(employee.getPassword())){
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_EDIT_FAILED);
        }
        //更新密码
        employee.setPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
        //更新修改时间
        employee.setUpdateTime(LocalDateTime.now());
        //更新修改人
        employee.setUpdateUser(BaseContext.getCurrentEmpId());
        employeeDao.updateById(employee);
    }
}
